﻿using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace VivendoByteToolkit.Helpers
{
    public static class TextBoxHelper
    {
        public static bool GetAutoSelectAll(DependencyObject obj)
        {
            return (bool)obj.GetValue(AutoSelectAllProperty);
        }

        public static void SetAutoSelectAll(DependencyObject obj,
            bool value)
        {
            obj.SetValue(AutoSelectAllProperty, value);
        }

        public static readonly DependencyProperty AutoSelectAllProperty =
            DependencyProperty.RegisterAttached("AutoSelectAll",
            typeof(bool),
            typeof(TextBoxHelper),
            new PropertyMetadata(null,
            new PropertyChangedCallback(Setup)));

        private static void Setup(DependencyObject obj,
            DependencyPropertyChangedEventArgs e)
        {
            TextBox tb = obj as TextBox;

            if (tb != null)
            {
                bool oldValue = (bool)e.OldValue;
                bool newValue = (bool)e.NewValue;

                if (oldValue == false && newValue == true)
                {
                    tb.GotFocus += tb_GotFocus;
                }
                else if (oldValue == true && newValue == false)
                {
                    tb.GotFocus -= tb_GotFocus;
                }
            }
        }

        static void tb_GotFocus(object sender, RoutedEventArgs e)
        {
            TextBox tb = sender as TextBox;

            if (tb != null)
            {
                tb.SelectAll();
            }
        }
    }
}